package com.binguo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.binguo.api.form.FaceForm;
import com.binguo.api.form.HZShiMingKaFaceBindForm;
import com.binguo.api.form.HZShiMingKaQueryForm;
import com.binguo.api.form.HZShiMingKaRechargeForm;
import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import com.binguo.api.service.PayCardService;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.model.model.*;
import com.binguo.model.repository.CustomerRechargeRepository;
import com.binguo.model.repository.ShiminkaFaceBindingRepository;
import com.binguo.service.CustomerService;
import com.binguo.service.ShopService;
import com.binguo.thirdPay.hzShiMing.HZShiMingFaceService;
import com.binguo.thirdPay.hzShiMing.HZShiMingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.io.File;
import java.util.Date;
import java.util.UUID;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

/**
 * @author yuritian
 * @Title: HZShiMingKaController
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-08-2013:32
 */
@Api(tags = "杭州市民卡接口")
@RestController
@RequestMapping
public class HZShiMingKaController {

    @Resource
    HZShiMingService hzShiMingService;

    @Resource
    HZShiMingFaceService hzShiMingFaceService;

    @Resource
    CustomerService customerService;

    @Autowired
    ShiminkaFaceBindingRepository shiminkaFaceBindingRepository;

    @Resource
    ShopService shopService;

    @Autowired
    CustomerRechargeRepository customerRechargeRepository;

    @Resource
    PayCardService payCardService;

    private String ipAddress;

    public HZShiMingKaController(){
        this.ipAddress = System.getenv().get("ipAddress");
    }


    @PostMapping(value = "/api/shimingka/query", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "市民卡查询", notes = "")
    public Result query(@RequestBody @Valid HZShiMingKaQueryForm form){
        JSONObject result = hzShiMingService.queryIdent(form.getCardNo());
        Customer customer = customerService.findSMKCustomerByCardNo(result.getString("cardnumber"));
        if (customer != null) {
            String SMKAccountBalance  = customerService.getSMKAcountBalance(customer);
            if (SMKAccountBalance!=null){
                result.put("smkaccountbalance", SMKAccountBalance);
            }else {
                result.put("yunpengMsg","市民卡查询故障");
            }
        }else {
            result.put("yunpengMsg","会员未建档");
        }
        return ResultGenerator.genSuccessResult(result);
    }


    @PostMapping(value = "/api/shimingka/faceBind", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "绑定", notes = "")
    public Result faceBind(@RequestBody @Valid HZShiMingKaFaceBindForm form){

        System.out.println(form.getCardKind());
        System.out.println(form.getCardNo());

        form.setImageBase64(form.getImageBase64().replaceAll("\r|\n", ""));

        ThreadManager.executorService.submit(new Runnable() {
            @Override
            public void run() {
                String uuid = UUID.randomUUID().toString();
                StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/faces/")
                            .append(0);

                /*StringBuffer outputFilepathStringBuffer = new StringBuffer("C:/Program Files (x86)/apache-tomcat-8.5.47/webapps/ROOT/")
                        .append(0);*/

                File dirOutput = new File(outputFilepathStringBuffer.toString());
                if (!dirOutput.exists()) {
                    dirOutput.mkdir();
                }
                String newFileName = outputFilepathStringBuffer.append("/").append(uuid).append(".png").toString();

                String httpFileName = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/images/faces/")
                            .append(0).append("/").append(uuid).append(".png").toString();

                /*String httpFileName = new StringBuffer("http://")
                        .append("123.206.224.209")
                        .append(":8080/")
                        .append(0).append("/").append(uuid).append(".png").toString();*/

                ImageBase64Util.base64StringToImage(form.getImageBase64(), newFileName);


                ShiminkaFaceBinding shiminkaFaceBinding = new ShiminkaFaceBinding();
                shiminkaFaceBinding.setCreatedtime(new Date());
                shiminkaFaceBinding.setFaceurl(httpFileName);
                shiminkaFaceBindingRepository.save(shiminkaFaceBinding);
            }
        });
        JSONObject result =  customerService.createYpCustomerBySMK(form.getCertNo(),form.getName(),form.getCardNo(),form.getCardKind(),form.getImageBase64(),form.getPhone());
        System.out.println(result);
        //hzShiMingService.faceBind(form.getImageBase64(),form.getCertNo(),form.getName(),form.getCardNo(),form.getCardKind());
        return ResultGenerator.genSuccessResult(result);

    }

    @PostMapping(value = "/api/shimingka/recharge", produces = APPLICATION_JSON_VALUE)
    public Result recharge (@RequestBody @Valid HZShiMingKaRechargeForm form){
        Customer customer = customerService.findSMKCustomerByCardNo(form.getCardNo());

        if (customer == null){
            throw new ServiceException("用户未建档,请先建档");
        }
        String SMKAccountBalance  = customerService.getSMKAcountBalance(customer);
        if (SMKAccountBalance == null){
            SMKAccountBalance = "0";
        }
        Shop shop = shopService.findShopById(form.getShopId());
        if (!hzShiMingService.recharge(form.getCardNo(),form.getCardKind(),form.getTxnamt(),shop.getShiminkaRechargeShopid())){
            throw new ServiceException("市民卡充值失败");
        }
        CustomerRecharge customerRecharge = new CustomerRecharge();
        customerRecharge.setRechargeCardAmount(Long.parseLong(SMKAccountBalance));
        customerRecharge.setRechargeCustomerid(customer.getId());
        customerRecharge.setRechargeCustomerName(customer.getName());
        customerRecharge.setRechargeCustomerPhone(customer.getPhone());
        customerRecharge.setRechargeDate(new Date());
        customerRecharge.setRechargeMoney(Integer.parseInt(form.getTxnamt()));
        customerRecharge.setRechargeShopid(form.getShopId());
        customerRecharge.setRechargeType(6);
        customerRecharge.setRechargeCustomerGroupid(0);
        customerRechargeRepository.save(customerRecharge);

        return ResultGenerator.genSuccessResult("");
    }


    @PostMapping(value = "/api/shimingka/findFace", produces = APPLICATION_JSON_VALUE)
    public Result findFace (@RequestBody @Valid FaceForm form){
        form.setFaceUrl(form.getFaceUrl().replaceAll("\r|\n", ""));
        JSONObject faceResult = hzShiMingFaceService.queryFace(form.getFaceUrl());
        if (faceResult == null){
            return null;
        }
        String imgToken = faceResult.getString("smkFaceToken");

        JSONObject result = hzShiMingService.faceQuery(imgToken);
        if (result == null){
            return null;
        }
        String certNo = result.getString("certNo");
        Customer customer = customerService.findSMKCustomer(certNo);
        String SMKAccountBalance  = customerService.getSMKAcountBalance(customer);
        if (SMKAccountBalance!=null){
            result.put("smkaccountbalance", SMKAccountBalance);
        }else {
            result.put("yunpengMsg","市民卡查询故障");
        }
        PayCard payCard = payCardService.getPayCard(form.getShopId(),customer.getId());
        if (payCard != null){
            result.put("yunPengCardNo",payCard.getCardno());
        }else {
            result.put("yunPengCardNo","");
        }

        return ResultGenerator.genSuccessResult(result);
    }
}
